package eerbaar.shared.persist.internal.lib;

import java.util.ArrayList;
import java.util.List;

import eerbaar.level.IMessage;
import eerbaar.level.IMessages;
import eerbaar.level.LevelFactory;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class MessagesPersister implements IPersister<IMessages> {

    public static final String NAME = "messages";

    private IMessages target;

    public MessagesPersister() {
        //
    }

    public MessagesPersister(IMessages wrapper) {
        this.target = wrapper;
    }

    public MessagesPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IMessages> getRegistertedInterface() {
        return IMessages.class;
    }

    @Override
    public ISaver<?>[] getSavableChildren() {

        List<MessagePersister> result = new ArrayList<MessagePersister>();

        IMessage[] a = this.target.getMessages();
        for (IMessage e : a) {
            MessagePersister p = new MessagePersister(e);
            result.add(p);
        }

        return result.toArray(new MessagePersister[] {});
    }

    @Override
    public String getSavableName() {

        return NAME;
    }

    @Override
    public IMessages getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> savable) {
        return false;
    }

    @Override
    public IMessages load(INode node) {
        assert (node != null);

        IMessages result = LevelFactory.createMessages();

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);

        List<INode> list = NodeCmdFactory.findChildren(node,
                MessagePersister.NAME);
        for (INode n : list) {
            try {
                IMessage msg = service.load(IMessage.class, n);
                result.addMesssage(msg);
            } catch (GameException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IMessages obj) {
        this.target = obj;
    }

}
